import { useState } from "react"
import {
  FlatList,
  Image,
  ImageStyle,
  ListRenderItem,
  Pressable,
  ScrollView,
  TextStyle,
  View,
  ViewStyle,
} from "react-native"

import { Screen, Text } from "@/components"
import { useAppTheme } from "@/theme/context"
import { $styles } from "@/theme/styles"
import type { ThemedStyle } from "@/theme/types"

type GalleryItemType = "image" | "text" | "mixed"

interface GalleryItem {
  id: string
  type: GalleryItemType
  title: string
  description?: string
  content?: string
  imageUrl?: string
  createdAt: string
}

const galleryFixtures: GalleryItem[] = [
  {
    id: "gallery-image-1",
    type: "image",
    title: "月光下的浮空城",
    description: "用户使用 Octopus 的图像模型生成，灵感来源于吉卜力动画。",
    imageUrl:
      "https://images.unsplash.com/photo-1522844990619-4951c40f7eda?auto=format&fit=crop&w=600&q=80",
    createdAt: "2 小时前",
  },
  {
    id: "gallery-text-1",
    type: "text",
    title: "角色设定摘要",
    content:
      "一位来自海底的旅行者，擅长与鲸鱼沟通，背负着修复珊瑚森林的使命。她随身携带一盏会发光的贝壳灯。",
    createdAt: "昨天",
  },
  {
    id: "gallery-mixed-1",
    type: "mixed",
    title: "图文故事《海风邮差》",
    description: "创作者上传的手绘插画，并配上短文描述故事的背景。",
    content: "他每天乘着海风，将瓶中信送往远方的岛屿。",
    imageUrl:
      "https://images.unsplash.com/photo-1526313199968-70e399ffe791?auto=format&fit=crop&w=600&q=80",
    createdAt: "3 天前",
  },
  {
    id: "gallery-image-2",
    type: "image",
    title: "用户上传：手绘机甲",
    description: "来自社区的手绘作品，展示了赛博朋克风的守护者。",
    imageUrl:
      "https://images.unsplash.com/photo-1618004912476-29818d81ae2e?auto=format&fit=crop&w=600&q=80",
    createdAt: "上周",
  },
]

const filterOptions: { key: "all" | GalleryItemType; label: string }[] = [
  { key: "all", label: "全部" },
  { key: "image", label: "图片" },
  { key: "text", label: "文字" },
  { key: "mixed", label: "图文" },
]

export default function GalleryPage() {
  const { themed, theme } = useAppTheme()
  const [activeFilter, setActiveFilter] = useState<(typeof filterOptions)[number]["key"]>("all")

  const filteredItems =
    activeFilter === "all"
      ? galleryFixtures
      : galleryFixtures.filter((item) => item.type === activeFilter)

  const renderGalleryItem: ListRenderItem<GalleryItem> = ({ item, index }) => {
    const isLeftColumn = index % 2 === 0
    return (
      <Pressable
        style={[
          themed($card),
          {
            marginRight: isLeftColumn ? theme.spacing.sm : 0,
          },
        ]}
        accessibilityRole="button"
        onPress={() => {
          if (__DEV__) {
            console.log(`Open gallery item: ${item.id}`)
          }
        }}
      >
        <View style={themed($cardHeader)}>
          <Text weight="medium" size="md" numberOfLines={1} text={item.title} />
          <Text size="xxs" style={themed($cardMeta)} text={item.createdAt} />
        </View>

        {item.imageUrl ? (
          <Image source={{ uri: item.imageUrl }} style={themed($cardImage)} resizeMode="cover" />
        ) : null}

        {item.description ? (
          <Text size="xs" style={themed($cardDescription)} text={item.description} />
        ) : null}

        {item.content ? (
          <View style={themed($contentNote)}>
            <Text size="xs" style={themed($contentNoteText)} text={item.content} />
          </View>
        ) : null}
      </Pressable>
    )
  }

  return (
    <Screen
      preset="fixed"
      safeAreaEdges={["top"]}
      style={themed($screen)}
      contentContainerStyle={$styles.flex1}
    >
      <View style={themed($header)}>
        <Text weight="medium" size="lg" text="创作图库" />
        <Text size="xs" style={themed($subtitle)} text="浏览 Octopus 用户最近的灵感作品" />
      </View>

      <View style={themed($filterRow)}>
        {filterOptions.map((filter) => {
          const isActive = filter.key === activeFilter
          return (
            <Pressable
              key={filter.key}
              style={[themed($filterChip), isActive && themed($filterChipActive)]}
              onPress={() => setActiveFilter(filter.key)}
              accessibilityRole="button"
            >
              <Text
                size="xs"
                weight={isActive ? "medium" : "normal"}
                style={themed(isActive ? $filterChipTextActive : $filterChipText)}
                text={filter.label}
              />
            </Pressable>
          )
        })}
      </View>

      <FlatList
        data={filteredItems}
        renderItem={renderGalleryItem}
        keyExtractor={(item) => item.id}
        numColumns={2}
        columnWrapperStyle={themed($columnWrapper)}
        contentContainerStyle={themed($listContent)}
        showsVerticalScrollIndicator={false}
        ListEmptyComponent={
          <View style={themed($emptyState)}>
            <Text size="xs" style={themed($emptyStateText)} text="暂无内容，去创作一条吧！" />
          </View>
        }
      />
    </Screen>
  )
}

const $screen: ThemedStyle<ViewStyle> = ({ colors }) => ({
  flex: 1,
  backgroundColor: colors.background,
})

const $header: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingHorizontal: spacing.lg,
  paddingTop: spacing.lg,
  paddingBottom: spacing.md,
})

const $subtitle: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
  marginTop: 4,
})

const $filterRow: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingHorizontal: spacing.lg,
  paddingBottom: spacing.md,
  flexDirection: "row",
  gap: spacing.sm,
})

const $filterChip: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  paddingHorizontal: spacing.md,
  borderRadius: spacing.lg,
  borderWidth: 1,
  borderColor: colors.separator,
  backgroundColor: colors.palette.neutral100,
  height: 32,
  justifyContent: "center",
  alignItems: "center",
})

const $filterChipActive: ThemedStyle<ViewStyle> = ({ colors }) => ({
  backgroundColor: colors.tint,
  borderColor: colors.tint,
})

const $filterChipText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.text,
})

const $filterChipTextActive: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.palette.neutral100,
})

const $listContent: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  paddingHorizontal: spacing.lg,
  paddingBottom: spacing.xxl,
})

const $columnWrapper: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  marginBottom: spacing.lg,
})

const $card: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  flex: 1,
  backgroundColor: colors.palette.neutral100,
  borderRadius: spacing.md,
  padding: spacing.md,
  borderWidth: 1,
  borderColor: colors.separator,
  shadowColor: colors.palette.neutral800,
  shadowOpacity: 0.06,
  shadowRadius: 8,
  shadowOffset: { width: 0, height: 8 },
  elevation: 6,
})

const $cardHeader: ThemedStyle<ViewStyle> = ({ spacing }) => ({
  marginBottom: spacing.sm,
})

const $cardMeta: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
  marginTop: 4,
})

const $cardImage: ThemedStyle<ImageStyle> = ({ spacing }) => ({
  width: "100%",
  height: 120,
  borderRadius: spacing.sm,
  marginBottom: spacing.sm,
})

const $cardDescription: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
  marginBottom: 8,
})

const $contentNote: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  backgroundColor: colors.palette.neutral200,
  borderRadius: spacing.sm,
  padding: spacing.sm,
})

const $contentNoteText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.text,
  lineHeight: 20,
})

const $emptyState: ThemedStyle<ViewStyle> = ({ colors, spacing }) => ({
  borderWidth: 1,
  borderColor: colors.separator,
  borderStyle: "dashed",
  borderRadius: spacing.md,
  paddingVertical: spacing.xl,
  marginTop: spacing.xl,
  alignItems: "center",
})

const $emptyStateText: ThemedStyle<TextStyle> = ({ colors }) => ({
  color: colors.textDim,
})
